﻿using AutoMapper;
using Common.Enum;
using Entity.Finance.DTO.ExamineReimburse;
using Entity.Finance.Entity;
using Entity.Finance.View.ExamineReimburse;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.Finance
{
    public class ExamineReimburseService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * 自动映射
         */
        private readonly IMapper _mapper;

        /**
         * 构造注入
         */
        public ExamineReimburseService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取报销审批单列表
         */
        public async Task<RequestResponseModel<PageResult<ExamineReimburseView>>> GetExamineReimburseList(ExamineReimburseSearchDTO examineReimburseSearchDTO)
        {
            //筛选
            var query = _context.ExamineReimburseView
                .WhereIF(a => a.Code.Contains(examineReimburseSearchDTO.Code), !string.IsNullOrEmpty(examineReimburseSearchDTO.Code))
                .WhereIF(a => a.StaffCode.Contains(examineReimburseSearchDTO.Code) || a.StaffName.Contains(examineReimburseSearchDTO.Code), !string.IsNullOrEmpty(examineReimburseSearchDTO.Code))
                .WhereIF(a => a.Status == examineReimburseSearchDTO.Status, examineReimburseSearchDTO.Status != null)
                ;
            
            //返回列表
            var examineReiburse = await query
                .OrderByDescending(a => a.ExamineTime)
                .Page(examineReimburseSearchDTO.CurrentPage,examineReimburseSearchDTO.PageSize)
                .ToListAsync();

            //总数据量
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<ExamineReimburseView>(examineReiburse, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 审核通过报销审批单
         */
        public async Task<RequestResponseModel<string>> PassExamineReimburse(string Id)
        {
            //校验数据
            var query = await Valid.ValidId<ExamineReimburseModel>(_context.ExamineReimburse,Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效",Id);
            };

            //搜索日常报销单
            var dailyReimburse = await _context.DailyReimburse.FirstOrDefaultAsync(a => a.Id == query.ReimburseId);

            //更新数据
            query.Status = StateEnum.ExamStatus.审核通过;
            dailyReimburse.Status = StateEnum.ExamStatus.审核通过;

            //更新表
            _context.DailyReimburse.Update(dailyReimburse);
            _context.ExamineReimburse.Update(query);
            await _context.SaveChangesAsync();

            return RequestResponse.CreateResponse(200, "审核通过成功", Id);
        }
    }
}
